package com.play.trading_test.config;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CommonUtil {

    @Getter
    @Resource
    private ObjectMapper objectMapper;

    @SneakyThrows
    public <T> T convertBean(String str, Class<T> clazz) {
        return objectMapper.readValue(str, clazz);
    }

    @SneakyThrows
    public <T> T convertBean(String str, JavaType javaType) {
        return objectMapper.readValue(str, javaType);
    }

    @SneakyThrows
    public <T> T convertBean(Object obj, Class<T> clazz) {
        return convertBean(objectMapper.writeValueAsString(obj), clazz);
    }

    @SneakyThrows
    public String obj2Str(Object o) {
        return objectMapper.writeValueAsString(o);
    }

    public <T> List<T> json2List(String str, Class<T> clazz) {
        JavaType type = objectMapper.getTypeFactory().constructParametricType(List.class, clazz);
        try {
            return objectMapper.readValue(str, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> List<T> convertList(List<?> data, Class<T> clazz) {
        String s = obj2Str(data);
        return json2List(s, clazz);
    }


}
